﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CongregacaoOs.Data;
using CongregacaoOs.Business;
using System.IO;

namespace CongregacaoOs.WebForm.Cadastros
{
    public partial class GerenciamentoOS : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["DadosGerais"] == null) Response.Redirect("~/Cadastros/Account/Login.aspx");

            if (hfIndexAccordion.Value != "0") Page.Form.DefaultButton = btnBuscar.UniqueID;

            if (!IsPostBack)
            {
                AtualizarGrieView();
                AtualizarRegionais();
                AtualizarTipoOs();
                Session["idOs"] = "";
                Session["FilePath"] = "";

            }
        }

        public void AtualizarGrieView()
        {
            ccOsBus bus = new ccOsBus();
            ccOs ent = new ccOs();
            DateTime dataFiltro = DateTime.MinValue;
            string aTipoUsuario = "";

            GetServantFeatures1_Result dadosGerais = new GetServantFeatures1_Result();

            dadosGerais = (GetServantFeatures1_Result)Session["DadosGerais"];

            if (Session["TipoUsuario"] != null) aTipoUsuario = Session["TipoUsuario"].ToString();

            if (aTipoUsuario == "Local")
            {
                /*O.S que a minha ADM executará*/
                ent.idRegionalOut = dadosGerais.idRegional;
                ent.idDistritalOut = dadosGerais.idDistrital;
                ent.idAdmOut = dadosGerais.idAdm;

            }
            else if (aTipoUsuario == "Distrital")
            {
                /*O.S que a minha ADM executará*/
                ent.idRegionalOut = dadosGerais.idRegional;
                ent.idDistritalOut = dadosGerais.idDistrital;
                ent.idServoQAbriu = dadosGerais.idPessoa;

            }
            else if (aTipoUsuario == "Regional")
            {
                /*O.S que a minha ADM executará*/
                ent.idRegionalOut = dadosGerais.idRegional;

            }

            /*Filtros disponíveis a qualquer usuário*/
            ent.codigo = txtCodigoBuscar.Text != "" ? txtCodigoBuscar.Text.Trim() : "";
            ent.status = radioStatusFiltro.SelectedValue == "3" ? "" : radioStatusFiltro.SelectedValue;

            if (txtDataInicioBuscar.Text != "" && txtDatafimBuscar.Text != "")
            {
                ent.dataCriacao = txtDataInicioBuscar.Text != "" ? Convert.ToDateTime(txtDataInicioBuscar.Text.Trim()) : DateTime.MinValue;
                if (Convert.ToDateTime(txtDatafimBuscar.Text) >= Convert.ToDateTime(txtDataInicioBuscar.Text))
                {
                    dataFiltro = Convert.ToDateTime(txtDatafimBuscar.Text);
                }
            }
            else
            {
                txtDataInicioBuscar.Text = "";
                txtDatafimBuscar.Text = "";
                ent.dataCriacao = DateTime.MinValue;
                dataFiltro = DateTime.MinValue;
            }

            gvOs.DataSource = bus.OsSelectFull(ent, dataFiltro);
            gvOs.DataBind();
        }

        public void AtualizarTipoOs()
        {
            ccTipoOsBus bus = new ccTipoOsBus();
            ccTipoOs ent = new ccTipoOs();

            ent.idTipoOs = 0;
            ent.nome = "";
            dropTipoOS.DataSource = bus.TipoOsSelect(ent);
            dropTipoOS.DataBind();
        }



        public void AtualizarRegionais()
        {
            ccRegionalBus bus = new ccRegionalBus();
            ccRegional ent = new ccRegional();
            List<ccRegionalSelect_Result> listaResult = new List<ccRegionalSelect_Result>();

            listaResult = bus.RegionalSelect(ent);

            dropRegionalOut.DataSource = listaResult;
            dropRegionalOut.DataBind();
        }

        public void AtualizarDistritalOut()
        {
            ccDistritalBus bus = new ccDistritalBus();
            ccDistrital ent = new ccDistrital();

            if (dropRegionalOut.SelectedValue != "")
            {
                ent.idRegional = Convert.ToInt32(dropRegionalOut.SelectedValue);
                dropDistritalOut.DataSource = bus.DistritalSelect(ent);
                dropDistritalOut.DataBind();
            }
            else
            {
                dropDistritalOut.Items.Clear();
                dropAdmOut.Items.Clear();
                dropCidadeOut.Items.Clear();
                dropSetorOut.Items.Clear();
                dropServoQExecutara.Items.Clear();
            }

        }

        public void AtualizarAdmOut()
        {

            ccAdmBus bus = new ccAdmBus();
            ccAdm ent = new ccAdm();


            ent.idRegional = dropRegionalOut.SelectedValue != "" ? Convert.ToInt32(dropRegionalOut.SelectedValue) : 0;

            if (dropDistritalOut.SelectedValue != "")
            {
                ent.idDistrital = Convert.ToInt32(dropDistritalOut.SelectedValue);
                dropAdmOut.DataSource = bus.AdmSelect(ent);
                dropAdmOut.DataBind();
            }
            else
            {
                dropAdmOut.Items.Clear();
                dropCidadeOut.Items.Clear();
                dropSetorOut.Items.Clear();
                dropServoQExecutara.Items.Clear();
            }
        }

        public void AtualizarCidadeOut()
        {

            ccCidadeBus bus = new ccCidadeBus();
            ccCidade ent = new ccCidade();

            ent.idRegional = dropRegionalOut.SelectedValue != "" ? Convert.ToInt32(dropRegionalOut.SelectedValue) : 0;

            if (dropDistritalOut.SelectedValue != "" && dropAdmOut.SelectedValue != "")
            {
                ent.idDistrital = Convert.ToInt32(dropDistritalOut.SelectedValue);

                dropCidadeOut.DataSource = bus.CidadeSelectComboBox(ent);
                dropCidadeOut.DataBind();
            }
            else
            {
                dropCidadeOut.Items.Clear();
                dropSetorOut.Items.Clear();
                dropServoQExecutara.Items.Clear();

            }

        }

        public void AtualizarSetorOut()
        {
            ccSetorBus bus = new ccSetorBus();
            ccSetor ent = new ccSetor();

            if (dropCidadeOut.SelectedValue != "" && dropAdmOut.SelectedValue != "")
            {

                ent.idSetor = Convert.ToInt32(dropAdmOut.SelectedValue);
                dropSetorOut.DataSource = bus.SetorSelectByAdm(ent.idSetor);
                dropSetorOut.DataBind();
            }
            else
            {
                dropSetorOut.Items.Clear();
                dropServoQExecutara.Items.Clear();
            }
        }

        public void AtualizarServoQExecutara()
        {
            ccPessoaBus bus = new ccPessoaBus();
            ccPessoaComboBox_Result ent = new ccPessoaComboBox_Result();

            int idSetor = dropSetorOut.SelectedValue != "" ? Convert.ToInt32(dropSetorOut.SelectedValue) : 0;

            if (dropAdmOut.SelectedValue != "")
            {
                int idAdm = Convert.ToInt32(dropAdmOut.SelectedValue);

                dropServoQExecutara.DataSource = bus.PessoaComboBox(idSetor, idAdm);
                dropServoQExecutara.DataBind();
            }
            else
            {
                dropServoQExecutara.Items.Clear();
            }
        }




        public void SalvarArquivo()
        {
            string[] a = new string[1];

            if (!Directory.Exists("~/OSFiles")) Directory.CreateDirectory("~/OSFiles");


            if (fileUpLoad.FileName.Length > 0)
            {
                if (Session["AnexoAntigo"] != "" && Session["AnexoAntigo"] != null)
                    System.IO.File.Delete(Server.MapPath("~/OSFiles/") + Session["AnexoAntigo"].ToString());

                string auxFileName = System.DateTime.Now.Ticks.ToString() + fileUpLoad.FileName;
                fileUpLoad.SaveAs(Server.MapPath("~/OSFiles/") + auxFileName);

                Session["FilePath"] = auxFileName;
                Session.Timeout = 60;
            }
            else { Session["FilePath"] = ""; }
        }

        public void ControlarVisualizacao(bool IsReadOnly)
        {
            Session["idOs"] = "";
            txtDataPrazo.Enabled = IsReadOnly == true ? false : true;
            dropTipoOS.Enabled = IsReadOnly == true ? false : true;
            dropRegionalOut.Enabled = IsReadOnly == true ? false : true;
            dropDistritalOut.Enabled = IsReadOnly == true ? false : true;
            dropAdmOut.Enabled = IsReadOnly == true ? false : true;
            dropCidadeOut.Enabled = IsReadOnly == true ? false : true;
            dropSetorOut.Enabled = IsReadOnly == true ? false : true;
            dropServoQExecutara.Enabled = IsReadOnly == true ? false : true;
            checkEnviarEmail.Enabled = IsReadOnly == true ? false : true;
            txtTexto.Enabled = IsReadOnly == true ? false : true;
            txtTitulo.Enabled = IsReadOnly == true ? false : true;
            fileUpLoad.Enabled = IsReadOnly == true ? false : true;
            btnSalvar.Enabled = IsReadOnly == true ? false : true;
        }


        protected void dropRegionalOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDistritalOut();
        }



        protected void dropDistritalOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarAdmOut();
        }


        protected void dropAdmOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarCidadeOut();
        }

        protected void dropTipoOS_DataBound(object sender, EventArgs e)
        {
            dropTipoOS.Items.Insert(0, new ListItem("Escolha o Tipo de O.S...", String.Empty));
        }


        protected void dropRegionalOut_DataBound(object sender, EventArgs e)
        {
            dropRegionalOut.Items.Insert(0, new ListItem("Escolha a Regional...", String.Empty));
        }

        protected void dropDistritalOut_DataBound(object sender, EventArgs e)
        {
            dropDistritalOut.Items.Insert(0, new ListItem("Escolha a Distrital...", String.Empty));
        }

        protected void dropAdmOut_DataBound(object sender, EventArgs e)
        {
            dropAdmOut.Items.Insert(0, new ListItem("Escolha a Administração...", String.Empty));
        }

        protected void dropCidadeOut_DataBound(object sender, EventArgs e)
        {
            dropCidadeOut.Items.Insert(0, new ListItem("Escolha a Cidade...", String.Empty));
        }

        protected void dropSetorOut_DataBound(object sender, EventArgs e)
        {
            dropSetorOut.Items.Insert(0, new ListItem("Selecione o Setor...", String.Empty));
        }

        protected void dropServoQExecutara_DataBound(object sender, EventArgs e)
        {
            dropServoQExecutara.Items.Insert(0, new ListItem("Selecione a Servo...", String.Empty));
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {

            txtAnexo.Visible = false;
            imgAnexo.Visible = false;
            int aID = 0;
            string aCodigo = String.Empty;
            int aIdAdmOut = 0;
            int aIdServoQExecutara = 0;
            string aAdministracao = dropAdmOut.SelectedItem.Text;
            string aSetor = dropSetorOut.SelectedItem.Text;
            string aIdSetor = dropSetorOut.SelectedItem.Value;

            try
            {

                if (txtDataPrazo.Text == "")
                {
                    MessageWindow.MessageType = false;
                    MessageWindow.Texto = "Selecione o prazo!";
                    MessageWindow.ShowWindow();
                    return;
                }

                GetServantFeatures1_Result dadosGerais = new GetServantFeatures1_Result();
                dadosGerais = (GetServantFeatures1_Result)Session["DadosGerais"];
                ccOs ent = new ccOs();
                ccOsBus bus = new ccOsBus();

                if (Session["idOs"] != "" && Session["idOs"] != null) ent.idOs = Convert.ToInt32(Session["idOs"]);

                ///Dados de Entrada                
                ent.idRegionalIn = dadosGerais.idRegional;
                ent.idDistritalIn = dadosGerais.idDistrital;
                ent.idAdmIn = dadosGerais.idAdm;
                ent.idCidadeIn = dadosGerais.idCidade != null ? Convert.ToInt32(dadosGerais.idCidade) : 0;
                ent.idServoQAbriu = dadosGerais.idPessoa;


                ent.idRegionalOut = dropRegionalOut.SelectedValue != "" ? Convert.ToInt32(dropRegionalOut.SelectedValue) : 0;
                ent.idDistritalOut = dropDistritalOut.SelectedValue != "" ? Convert.ToInt32(dropDistritalOut.SelectedValue) : 0;
                ent.idAdmOut = dropAdmOut.SelectedValue != "" ? Convert.ToInt32(dropAdmOut.SelectedValue) : 0;
                aIdAdmOut = ent.idAdmOut != null ? Convert.ToInt32(ent.idAdmOut) : 0;

                ent.idCidadeOut = dropCidadeOut.SelectedValue != "" ? Convert.ToInt32(dropCidadeOut.SelectedValue) : 0;
                ent.idSetorOut = dropSetorOut.SelectedValue != "" ? Convert.ToInt32(dropSetorOut.SelectedValue) : 0;
                ent.idServoQExecutara = dropServoQExecutara.SelectedValue != "" ? Convert.ToInt32(dropServoQExecutara.SelectedValue) : 0;
                aIdServoQExecutara = dropServoQExecutara.SelectedValue != "" ? Convert.ToInt32(dropServoQExecutara.SelectedValue) : 0;
                ent.EnviarEmailSetor = checkEnviarEmail.Checked;

                ent.titulo = txtTitulo.Text;
                ent.texto = txtTexto.Text;

                if (fileUpLoad.FileName.Length == 0 && txtAnexo.Text != "")
                    ent.anexo = txtAnexo.Text;

                if (fileUpLoad.FileName.Length > 0)
                { 
                    SalvarArquivo();
                    ent.anexo = Session["FilePath"].ToString() != "" ? Session["FilePath"].ToString() : "";
                }

                if (fileUpLoad.FileName.Length == 0 && txtAnexo.Text == "") ent.anexo = "";

                


                

                if (lblCodigoID.Text == "")
                {
                    Random randomNumber = new Random();
                    ent.codigo = randomNumber.Next(10000000).ToString();
                    aCodigo = ent.codigo;
                }
                else
                {
                    ent.codigo = lblCodigoID.Text.Trim();
                    aCodigo = ent.codigo;

                }

                ent.dataPrazo = txtDataPrazo.Text.Trim() != "" ? Convert.ToDateTime(txtDataPrazo.Text.Trim()) : DateTime.MinValue;
                ent.idTipoOs = dropTipoOS.SelectedValue != "" ? Convert.ToInt32(dropTipoOS.SelectedValue) : 0;
                ent.dataCriacao = DateTime.Now;
                ent.status = "0"; //0=AGUARDANDO - 1=ATENDIMENTO - 2=CONCLUÍDA

                try
                {

                    aID = bus.OsSaveOrUpdate(ent);
                    Session["idOs"] = "";
                    AtualizarGrieView();
                    hfIndexAccordion.Value = "0";
                }
                catch (Exception)
                {
                    MessageWindow.MessageType = false;
                    MessageWindow.Texto = "Ocorreu um erro ao gerar a O.S. Tente novamente ou contate o suporte";
                    MessageWindow.ShowWindow();
                    return;
                }


                if (aID != 0)
                {
                    if (txtTexto.Text != "" && txtTitulo.Text != "")
                    {
                        ccPost ForumEnt = new ccPost();
                        ccPostBus ForumBus = new ccPostBus();
                        GetServantFeatures1_Result UserData = new GetServantFeatures1_Result();


                        ForumEnt.idOs = aID;
                        ForumEnt.titulo = txtTitulo.Text;
                        ForumEnt.dataCriacao = DateTime.Now;
                        ForumEnt.texto = txtTexto.Text;
                        ForumEnt.idServo = dadosGerais.idPessoa;
                        ForumBus.PostSaveOrUpdate(ForumEnt);
                    }
                }

                MessageWindow.MessageType = true;
                MessageWindow.Texto = "Ordem de Serviço salva com sucesso!";
                MessageWindow.ShowWindow();


            }
            catch (Exception errot)
            {

                throw new Exception(errot.Message);
                MessageWindow.MessageType = false;
                MessageWindow.Texto = "Ocorreu um erro ao salvar a O.S. Tente novamente ou contate o suporte: " + errot.Message;
                MessageWindow.ShowWindow();

                return;
            }

            try
            {
                using (ccSendEmail busEmail = new ccSendEmail())
                {
                    using (ClassEmail email = new ClassEmail())
                    {
                        email.Assunto = @"Portal de O.S - Nova O.S";

                        email.Menssagem = "<HEAD>" +
                                "<TITLE>Regional Ribeirão Preto</TITLE>" +
                                "<STYLE TYPE='text/css'>" +
                                "* { margin: 0 auto; width:100%; padding: 0px; }" +
                                "body { font-size: 80%;  font-family: 'Lucinda Grande', Verdana, Sans-Serif; margin: 0 auto; }" +
                                "h1 { font-size: 150%; font-weight: bold; color: white; }" +
                                "h2 { font-size: 110%; font-weight: bold; margin: 0 0 10px 20px; }" +
                                "p { font-size: 100%; line-height: 150%; margin: 20px; }" +
                                ".header { padding: 10px; border: 1px solid #000000; background-color: #336699; height: 40px; color: #EEEEEE; width: 100%; }" +
                                ".content { margin-left: 25px; }" +
                                "th { text-align: left; font-weight: bold; padding-right: 10px; }" +
                                ".footer { padding: 10px; border: 1px solid #000000; background-color: #336699; height: 20px; color: #EEEEEE; width: 100%; }" +
                                "</STYLE>" +
                                "</HEAD>" +
                                "<BODY>" +
                                "<TABLE>" +
                                "<TR><TD class='header'>" +
                                "<H1>Nova O.S(" + aCodigo + ")</H1>" +
                                "</TD></TR>" +
                                "<TR><TD>" +
                                "<P>" +
                                        "<br/><b>Setor que executará a O.S: </b>" + aSetor + "<br />" +
                                        "<b>Texto da solicitação:</b> " + txtTexto.Text + " <br />" +
                                        "<a href='http://www.ccbos.com.br'>Acessar O.S?</a> " +
                                        "<br/><br/><b>Não responda este e-mail</b>" +
                                "</P>" +
                                "</TD></TR>" +
                                "<TR><TD class='footer'>" +
                                "Grupo de Apoio Regional Ribeirão Preto" +
                                "</TD></TR>" +
                                "</TABLE>" +
                                "</BODY>" +
                                "</HTML>";

                        ccPessoa entPes = new ccPessoa();
                        ccPessoaBus busPes = new ccPessoaBus();

                        if (dropServoQExecutara.SelectedValue == "") checkEnviarEmail.Checked = false;

                        if (checkEnviarEmail.Checked)
                        {
                            string ServoEmail = busPes.GetEmailPessoaByID(aIdServoQExecutara);
                            email.ListofDestinatario.Add(ServoEmail);
                            busEmail.SendMail(email);

                            Functions.LimparCampos(this);
                            return;
                        }

                        List<String> listaDestinatarios = busPes.PessoaEmailBySetor(Convert.ToInt32(aIdSetor), aIdAdmOut);
                        foreach (var item in listaDestinatarios)
                        {
                            email.ListofDestinatario.Add(item);

                        }

                        busEmail.SendMail(email);


                        

                    }
                }


            }
            catch (Exception erro)
            {
                MessageWindow.MessageType = false;
                MessageWindow.Texto = "A O.S foi aberta mas ocorreu um erro ao enviar os e-mails de alerta.";
                MessageWindow.ShowWindow();
                return;
            }

            Functions.LimparCampos(this);

        }

        protected void btnVoltar_Click(object sender, EventArgs e)
        {
            hfIndexAccordion.Value = "0";
            Session["idOs"] = "";
            txtAnexo.Visible = false;
            imgAnexo.Visible = false;
            Functions.LimparCampos(this);
        }

        protected void gvOs_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = int.Parse(e.CommandArgument.ToString());
            HiddenField hdIdOs = null;
            HiddenField hdStatus = null;
            HiddenField hdIdUsuarioIn = null;
            HiddenField hdCodigo = null;

            if (e.CommandName == "EDITAR")
            {

                txtAnexo.Visible = true;
                imgAnexo.Visible = true;

                hdStatus = (gvOs.Rows[index].FindControl("hdStatus") as HiddenField);
                if (hdStatus.Value != "0")
                    ControlarVisualizacao(true);
                else
                {
                    ControlarVisualizacao(false);
                }

                hdIdUsuarioIn = (gvOs.Rows[index].FindControl("hdIdUsuarioIn") as HiddenField);

                hdIdOs = (gvOs.Rows[index].FindControl("hdIdOs") as HiddenField);
                Session["idOs"] = hdIdOs.Value;
                hdCodigo = (gvOs.Rows[index].FindControl("hdCodigo") as HiddenField);
                HiddenField hdDataCriacao = (gvOs.Rows[index].FindControl("hdDataCriacao") as HiddenField);
                HiddenField hdTitulo = (gvOs.Rows[index].FindControl("hdTitulo") as HiddenField);

                HiddenField hdTexto = (gvOs.Rows[index].FindControl("hdTexto") as HiddenField);

                HiddenField hdDataPrazo = (gvOs.Rows[index].FindControl("hdDataPrazo") as HiddenField);
                HiddenField hdTipoOs = (gvOs.Rows[index].FindControl("hdTipoOs") as HiddenField);


                HiddenField hdRegionalIn = (gvOs.Rows[index].FindControl("hdRegionalIn") as HiddenField);
                HiddenField hdDistritalIn = (gvOs.Rows[index].FindControl("hdDistritalIn") as HiddenField);
                HiddenField hdAdmIn = (gvOs.Rows[index].FindControl("hdAdmIn") as HiddenField);
                HiddenField hdCidadeIn = (gvOs.Rows[index].FindControl("hdCidadeIn") as HiddenField);
                HiddenField hdRegionalOut = (gvOs.Rows[index].FindControl("hdRegionalOut") as HiddenField);


                HiddenField hdDistritalOut = (gvOs.Rows[index].FindControl("hdDistritalOut") as HiddenField);
                HiddenField hdAdmOut = (gvOs.Rows[index].FindControl("hdAdmOut") as HiddenField);
                HiddenField hdCidadeOut = (gvOs.Rows[index].FindControl("hdCidadeOut") as HiddenField);
                HiddenField hdSetorOut = (gvOs.Rows[index].FindControl("hdSetorOut") as HiddenField);
                HiddenField hdAnexo = (gvOs.Rows[index].FindControl("hdAnexo") as HiddenField);
                Session["AnexoAntigo"] = hdAnexo.Value;

                HiddenField hdServoQExecutara = (gvOs.Rows[index].FindControl("hdServoQExecutara") as HiddenField);

                HiddenField hdEnviarEmailSetor = (gvOs.Rows[index].FindControl("hdEnviarEmailSetor") as HiddenField);

                if (hdEnviarEmailSetor.Value == "True")
                {
                    checkEnviarEmail.Checked = true;
                }
                else
                {
                    checkEnviarEmail.Checked = true;
                }

                lblCodigoID.Text = hdCodigo.Value.ToString();
                txtTitulo.Text = hdTitulo.Value.ToString();
                txtTexto.Text = hdTexto.Value.ToString();
                txtDataPrazo.Text = Convert.ToDateTime(hdDataPrazo.Value).ToString("dd/MM/yyyy");
                txtAnexo.Text = hdAnexo.Value;

                try
                {

                    AtualizarRegionais();
                    if (hdRegionalOut.Value != "" && dropRegionalOut.Items.FindByText(hdRegionalOut.Value) != null)
                        dropRegionalOut.Items.FindByText(hdRegionalOut.Value).Selected = true;

                    AtualizarDistritalOut();
                    if (hdDistritalOut.Value != "" && dropDistritalOut.Items.FindByText(hdDistritalOut.Value) != null)
                        dropDistritalOut.Items.FindByText(hdDistritalOut.Value).Selected = true;

                    AtualizarAdmOut();
                    if (hdAdmOut.Value != "" && dropAdmOut.Items.FindByText(hdAdmOut.Value) != null)
                        dropAdmOut.Items.FindByText(hdAdmOut.Value).Selected = true;

                    AtualizarCidadeOut();
                    if (hdCidadeOut.Value != "" && dropCidadeOut.Items.FindByText(hdCidadeOut.Value) != null)
                        dropCidadeOut.Items.FindByText(hdCidadeOut.Value).Selected = true;

                    AtualizarTipoOs();
                    if (hdTipoOs.Value != "" && dropTipoOS.Items.FindByText(hdTipoOs.Value) != null)
                        dropTipoOS.Items.FindByText(hdTipoOs.Value).Selected = true;

                    AtualizarSetorOut();
                    if (hdSetorOut.Value != "" && dropSetorOut.Items.FindByText(hdSetorOut.Value) != null)
                        dropSetorOut.Items.FindByText(hdSetorOut.Value).Selected = true;

                    AtualizarServoQExecutara();
                    if (hdServoQExecutara.Value != "" && dropServoQExecutara.Items.FindByValue(hdServoQExecutara.Value) != null)
                        dropServoQExecutara.Items.FindByValue(hdServoQExecutara.Value).Selected = true;


                    string a = hdAnexo.Value;

                    hfIndexAccordion.Value = "1";

                    return;
                }
                catch (Exception)
                {

                    throw;
                }


            }
            else if (e.CommandName == "FORUM")
            {
                hdStatus = (gvOs.Rows[index].FindControl("hdStatus") as HiddenField);
                hdIdUsuarioIn = (gvOs.Rows[index].FindControl("hdIdUsuarioIn") as HiddenField);
                hdCodigo = (gvOs.Rows[index].FindControl("hdCodigo") as HiddenField);              
                hdIdOs = (gvOs.Rows[index].FindControl("hdIdOs") as HiddenField);

                Session["StatusOs"] = hdStatus.Value;
                Session["idOs"] = hdIdOs.Value;
                Session["IdUsuarioAbriu"] = hdIdUsuarioIn.Value;
                Response.Redirect("~/Cadastros/ForumOs.aspx");
            }
        }

        protected void gvOs_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton img = (e.Row.FindControl("imgEditar") as ImageButton);
                img.CommandArgument = e.Row.RowIndex.ToString();

                ImageButton imgForum = (e.Row.FindControl("imgForum") as ImageButton);
                imgForum.CommandArgument = e.Row.RowIndex.ToString();


                ImageButton imgStatus = (e.Row.FindControl("imgStatus") as ImageButton);


                switch (imgStatus.CommandArgument)
                {
                    case "0":
                        imgStatus.ImageUrl = @"~\Images\StatusImageOS\Aguardando.png";
                        imgStatus.ToolTip = "Aguardando Atendimento";
                        break;
                    case "1":
                        imgStatus.ImageUrl = @"~\Images\StatusImageOS\SendoAtendida.png";
                        imgStatus.ToolTip = "Em atendimento";
                        break;
                    case "2":
                        imgStatus.ImageUrl = @"~\Images\StatusImageOS\Concluida.png";
                        imgStatus.ToolTip = "Concluída";
                        break;
                }
            }
        }

        protected void btnGerarOs_Click(object sender, EventArgs e)
        {
            Session["idOs"] = "";
            hfIndexAccordion.Value = "1";
            Functions.LimparCampos(this);
            ControlarVisualizacao(false);
        }

        protected void gvOs_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            AtualizarGrieView();
            gvOs.PageIndex = e.NewPageIndex;
            gvOs.DataBind();
        }

        protected void imgAnexo_Click(object sender, ImageClickEventArgs e)
        {
            DownloadFile(txtAnexo.Text);
        }

        public void DownloadFile(string fileName)
        {
            Response.Clear();
            Response.ContentType = @"application\octet-stream";
            System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath("~/OsFiles/") + fileName);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            Response.Flush();
        }



        protected void dropSetorOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarServoQExecutara();
        }

        protected void dropCidadeOut_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarSetorOut();
        }


        protected void dropSetorFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarGrieView();
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            AtualizarGrieView();
        }

        protected void radioStatusFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarGrieView();
        }

        protected void radioEnviaEmail_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void dropServoQExecutara_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropServoQExecutara.SelectedIndex == 0)
                checkEnviarEmail.Checked = false;
        }

        protected void checkEnviarEmail_CheckedChanged(object sender, EventArgs e)
        {
            if (dropServoQExecutara.SelectedIndex == 0)
                checkEnviarEmail.Checked = false;
        }



    }
}